// src/stores/userStore.ts
import { defineStore } from "pinia";
import type { Status } from "@/types/Status";
import type { Recal } from "@/types/Recall";
import { HomeAPI } from "@/api/HomeAPI";
import { ElMessage, ElMessageBox } from "element-plus";
import ajaxsuccess from "@/utils/ajaxsuccess";


type State = {
   recallist:{
    result: Recal[];
    status: Status;
   }
};

type Getters = {};

type Actions = {
  //添加\编辑回忆录
  add_Recall(history:Recal):Promise<boolean>,
  //获取回忆录列表
  get_Recall():Promise<void>,
  //删除回忆录
  delete_Recall(nid:string):Promise<void>
  
};

export const recallStore = defineStore<"recall", State, Getters, Actions>(
  "recall",
  {
    state: () => ({
        //回忆录列表
        recallist:{
            result:[],
            status: 'idle'
           }
    }
     
     ),
     actions:{
      //添加回忆录
    async add_Recall(history){
      const response = await HomeAPI.history_add(history);
      //调用弹出函数
      const relboe =  ajaxsuccess(response)
      if(!relboe){
        this.get_Recall()
        return relboe
      }
      return relboe
    },
    //获取回忆录
    async get_Recall(){
        //更新请求状态
        this.recallist.status = "loading"
        try{
         //发送请求获取数据
        const response =  await HomeAPI.get_recall()
      
        //保存数据
        this.recallist.result = response.data
        //更改状态为成功态
        this.recallist.status = "success"
        }catch(error){
        //更改状态为失败态
        this.recallist.status = 'error'
        }
    },
    //删除回忆录
    async delete_Recall(nid){
    
      
      ElMessageBox.confirm("确认删除此回忆录吗?", "回忆录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const response= await HomeAPI.delete_recall(nid)
        //调用弹出函数
        const relboe =  ajaxsuccess(response)
        if(!relboe){
          this.get_Recall()
          return relboe
        }
       
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      });
    }
     },
   
  }
);